cc.Class({
    extends: cc.Component,

    properties: {
        blackBg: cc.Node,
        rotateSprite: cc.Node,
        rotateSpeed: 2,
        _referenceCount: 0,
    },

    // use this for initialization
    onLoad: function () {
        // 单例设置为常驻节点
        cc.game.addPersistRootNode(this.node);
        // 赋值给全局方法
        GameToast.showLoading = (isVisible, delayTime) => {
            this.show(isVisible, delayTime);
        };
        // 默认不显示loading
        // this.node.active = false;
        // 不传递透明度
        this.blackBg.cascadeOpacity = false;
        // 添加touch遮罩
        this.addComponent('TouchMask');
        // 动画
        // this.schedule(this.rotationUpdate, 0.03);
        this.rotateSprite.runAction(cc.repeatForever(cc.rotateBy(this.rotateSpeed, 360)));
        // 设置位置
        this.getComponent(cc.Widget).enabled = true;

        cc.logEx('loading初始化');
    },

    show: function(isVisible, delayTime) {
        if (isVisible) {
            this._show(delayTime);
        }
        else {
            this._hide();
        }
    },

    _show: function(delayTime) {
        this._referenceCount++;
        if (this._referenceCount !== 1) {
            return;
        }
        cc.logEx('打开loading');
        this.node.active = true;
        // 延迟显示颜色遮罩
        this.blackBg.x = 10000;
        if (delayTime === undefined || delayTime === null) delayTime = 0.5;
        this.node.runAction(cc.sequence(
            cc.delayTime(delayTime),
            cc.callFunc(() => this.blackBg.x = 0)
        ));
    },
    _hide: function() {
        if (this._referenceCount <= 0) {
            cc.error('loading引用计数错误', this._referenceCount);
            return;
        }

        this._referenceCount--;
        if (this._referenceCount !== 0) {
            return;
        }
        cc.logEx('关闭loading');
        this.node.active = false;
        this.blackBg.x = 10000;
        this.node.stopAllActions();
    },

    // rotationUpdate: function() {
    //     this.rotateSprite.rotation -= 360/8;
    //     if (this.rotateSprite.rotation === -360) {
    //         this.rotateSprite.rotation = 0;
    //     }
    // },
});